"use strict";

const axios = require("axios");
const urljoin = require("url-join");
const semver = require("semver");
const log = require("@wenjun-cli/log");

// 获取NPM包的信息
function getNpmInfo(npmName, isOriginalRegistry) {
  // TODO 获取包的版本号
  if (!npmName) {
    return null;
  }
  const registry = isOriginalRegistry || getDefaultRegistry();
  const npmInfoUrl = urljoin(registry, npmName);
  log.info("??????? get-npm-info", npmName, registry, npmInfoUrl);
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      }
      return null;
    })
    .catch((err) => {
      return Promise.reject(err);
    });
}

// 初始化NPM API镜像源
function getDefaultRegistry(isOriginal = false) {
  return isOriginal
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}

// 获取真正的版本号
async function getNpmVersions(npmName, isOriginalRegistry) {
  const data = await getNpmInfo(npmName, isOriginalRegistry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return null;
  }
}

// 获取满足条件的版本号
function getSemverVersions(baseVersion, versions) {
  return versions
    .filter((version) => semver.satisfies(version, `^${baseVersion}`))
    .sort((a, b) => {
      return semver.gt(b, a);
    });
}

// 获取最终满足条件的version
async function getNpmSemverVersion(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
}

// 返回最终版本号
async function getNpmLatestVersion(npmName, registry) {
  let versions = await getNpmVersions(npmName, registry);
  if (versions) {
    versions = versions.sort((a, b) => {
      if (semver.lt(a, b)) {
        return 1;
      } else {
        return -1;
      }
    });
    return versions[0];
  }
  return null;
}

module.exports = {
  getNpmSemverVersion,
  getDefaultRegistry,
  getNpmLatestVersion,
};
